import urllib
import urllib2
import re
import sys
from BeautifulSoup import BeautifulStoneSoup      # For processing XML

scriptName = sys.modules['__main__'].__scriptname__


class Adlm:

    USER_AGENT = 'XBMC/1.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14'
    BASE_URL = 'http://www.sauleil.com/xbmc/request.php?key=081E96D85F1A11E0A4EF3E7CDFD72085'
    PICTURE_URL = 'http://www.sauleil.com/xbmc/picture.php/'
    THUMB_URL = 'http://www.sauleil.com/xbmc/'
    
    def getXmlFromUrl(self, url):
        """Returns XML from a URL"""
        try:
            print '[%s] %s attempting to open %s' % (scriptName, __name__, url)
            req = urllib2.Request(url)
            req.add_header('User-Agent', self.USER_AGENT)
            response = urllib2.urlopen(req)
            xml=response.read()
            response.close()
            return xml
        except urllib2.HTTPError, error:
            print '[%s] %s error opening %s' % (scriptName, __name__, url)
            print error.msg, error.code, error.geturl()
            try:
                import xbmcgui
                xbmcgui.Dialog().ok(error.msg, '%s\n%s' % (error.code, error.geturl()))
            except:
                pass
        return ''
    
    def getCategories(self):
        """Create an ordered list of [{provider, category}]"""
        try:
            self.categories
        except:
            print '[%s] %s cache list categories' % (scriptName, __name__)
            self.categories = list()
            xml = self.getXmlFromUrl(self.BASE_URL + '&action=category')
            soup = BeautifulStoneSoup(xml)
            items=soup.findAll('category')
            for item in items:
                self.categories.append({'provider': item['provider'], 'category': item['category']})
        return self.categories
        
    def getSeries(self, provider, category):
        """Create an ordered list of of series"""
        key = provider + category
        try:
            self.series
        except:
            self.series = {}
        try:
            self.series[key]
        except:
            print '[%s] %s cache series' % (scriptName, __name__)
            s = list()
            params = urllib.urlencode({'action': 'series', 'provider': provider, 'category': category})
            xml = self.getXmlFromUrl(self.BASE_URL + '&' + params)
            soup = BeautifulStoneSoup(xml)
            items=soup.findAll('serie')
            for item in items:
                s.append({'serieId':item['id'], 'model':item['model'], 'serie':item['serie'], 'category':item['category'], 'providerName':item['pname'], 'providerNumber': item['pnumber'], 'idolhasinfo': item['idolhasinfo'], 'idolbirthday': item['idolbirthday'], 'idolbirthplace': item['idolbirthplace'], 'idolheight': item['idolheight'], 'idolsizes': item['idolsizes'], 'idolcup': item['idolcup'], 'idolbloodtype': item['idolbloodtype'], 'idolinterests': item['idolinterests'], 'idolthumb': self.THUMB_URL + item['idolthumb']})
            self.series[key] = s
        return self.series[key]
        
    def getPictures(self, serieId):
        try:
            self.serie
        except:
            self.serie = {}
        try:
            self.serie[serieId]
        except:
            print '[%s] %s cache serie pictures' % (scriptName, __name__)
            params = urllib.urlencode({'action': 'list', 'serieId': serieId})
            xml = self.getXmlFromUrl(self.BASE_URL + '&' + params)
            soup = BeautifulStoneSoup(xml)
            items=soup.findAll('picture')
            s = list()
            for item in items:
                s.append({'id': item['id'], 'serieId':item['serieid'], 'number':item['number']})
            self.serie[serieId] = s
        return self.serie[serieId]
        
    def getPictureUrl(self, pictureId):
        return self.PICTURE_URL + pictureId + '.jpg'  # TODO: maybe store the file format so it's not hardcoded.
        
    def searchSeries(self, terms):
        print '[%s] %s search' % (scriptName, __name__)
        xml = self.getXmlFromUrl(self.BASE_URL + '&action=search&terms=' + urlencode(terms))
        soup = BeautifulStoneSoup(xml)
        items=soup.findAll('serie')
        searchResults = list()
        for item in items:
            searchResults.append({'id': item['id'], 'model': item['model'], 'serie': item['serie'], 'provider': item['pname'], 'category': item['category'], 'idolhasinfo': item['idolhasinfo'], 'idolbirthday': item['idolbirthday'], 'idolbirthplace': item['idolbirthplace'], 'idolheight': item['idolheight'], 'idolsizes': item['idolsizes'], 'idolcup': item['idolcup'], 'idolbloodtype': item['idolbloodtype'], 'idolinterests': item['idolinterests'], 'idolthumb': self.THUMB_URL + item['idolthumb']})
        return searchResults
        
    def getRandomPictures(self, index = -1):
        print '[%s] %s cache serie' % (scriptName, __name__)
        results = list()
        url = self.BASE_URL + '&action=slideshow'
        if index >= 0:
            url = url + '&index=' + str(index)
        xml = self.getXmlFromUrl(url)
        soup = BeautifulStoneSoup(xml)
        items=soup.findAll('picture')
        imagesResults = list()
        for item in items:
            imagesResults.append({'id': item['key'], 'serieId': item['serieid'], 'serie': item['serie'], 'provider': item['provider'], 'category': item['category'], 'model': item['model'], 'idolhasinfo': item['idolhasinfo'], 'idolbirthday': item['idolbirthday'], 'idolbirthplace': item['idolbirthplace'], 'idolheight': item['idolheight'], 'idolsizes': item['idolsizes'], 'idolcup': item['idolcup'], 'idolbloodtype': item['idolbloodtype'], 'idolinterests': item['idolinterests'], 'idolthumb': self.THUMB_URL + item['idolthumb']})
        return imagesResults
    
    def getModelInfo(self, model):
        return ['text\nwith\nenter', 'activities']
